/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package banksystem;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;

/**
 *
 * @author conra_000
 */
public class Database {
	ObjectContainer mDB = null;
	User mUser = null;
	
	public Database(String dBFile) {
		EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
		configuration.common().objectClass(User.class).cascadeOnUpdate(true);
		mDB = Db4oEmbedded.openFile(configuration, dBFile);
	}
	
	public Database() { 
		this("DatabaseStorage.yap");
	}
	
	public User login(String userName, String password) {
		mUser = getUser(userName,password);
		return mUser;
	}
	
	private User getUser(String userName, String password) {
		User queryUser = new User(userName, password);
		ObjectSet retrievedUsers = mDB.queryByExample(queryUser);
		
		if(retrievedUsers.hasNext()) {
			User returnedUser = (User) retrievedUsers.next();
			return returnedUser;
		} else {
			return null; //username/password has no user
		}
	}
	
	// creates a new user
	public User createUser(String userName, String password) {
		if(getUser(userName, null) == null) {
			mUser = new User(userName, password);
			return mUser;
		} else {
			return null; //username is not unique;
		}
	}
	
	// saves mUser to database, or updates with recursion if already exists
	public void saveUser() {
		if(mUser != null) {
			mDB.store(mUser);
			mDB.commit();
		}
	}
	
	public void Dispose() {
		mDB.close();
	}
}
